package com.kingyun.gpsinspection.purificationservice.services.tdm.outerservice.impl;

import com.alibaba.fastjson.JSON;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.common.utils.FileTypeUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.TdmFileMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.TdmProblemMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.File;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.Problem;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.ProblemWebService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by sugongche on 2016/11/22.
 */
public class ProblemWebServiceImpl implements ProblemWebService {
    public Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TdmProblemMapper tdmProblemMapper;
    @Autowired
    private TdmFileMapper tdmFileMapper;

    /**
     * 保存
     * 注意：解开启事务，不能抛异常
     *
     * @param problem
     * @param uploadFiles
     * @param deletedFiles
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int save(Problem problem, String uploadFiles, String deletedFiles) {
        if (problem == null) {
            return 0;
        }
        logger.info("save -- 开始");
        problem.setCreateTime(new Date());
        problem.setModifyTime(new Date());
        int a = tdmProblemMapper.insert(problem);

        if (StringUtils.isNotBlank(uploadFiles)) {
            //强制转换成集合
            List<File> listFiles = JSON.parseArray(uploadFiles, File.class);

            //重新设置附件属性
            for (int i = 0; i < listFiles.size(); i++) {
                File _file = listFiles.get(i);
                //设置主键
                _file.setFileId(UniqueUtil.uuid());
                //设置业务数据id
                _file.setBusinessId(problem.getProblemId());
                _file.setFileType((short) FileTypeUtil.getFileTypeByFileName(_file.getFileName()));
            }

            //必须判断非空
            if (listFiles != null && listFiles.size() > 0) {
                a += tdmFileMapper.insertByList(listFiles);
            }
        }

        //删除的附件不为空的情况
        if (StringUtils.isNotBlank(deletedFiles)) {
            //强制转换成集合
            List<File> listFiles = JSON.parseArray(deletedFiles, File.class);
        }
        logger.info("save -- 结束");
        return a;
    }
}
